import React, {Component, PureComponent} from 'react'
import {View, Text, TouchableOpacity, Image, StyleSheet, SectionList, Dimensions,SafeAreaView, FlatList,DeviceEventEmitter} from 'react-native'
import {commonStyle} from './commonStyle'
const shoppingCartData = require('./ShoppingCartData.json')
const {width, height} = Dimensions.get('window')
import EmptyCouponView from "../../../widget/CommonEmptyView";
import api from '../../../api/api'
import method from '../../../api/method'
import NetTool from '../../../api/NetTool'
import {fetchGetRequest, fetchPostRequest} from "../../../api/NetworkTool";
import UseCouponDialog from '../../../widget/dialog/UseCouponDialog'
import Tips from 'react-native-root-tips'
import color from "../../../widget/color";
import XPay from "react-native-puti-pay";
import {NavigationActions} from "react-navigation";
import BuySuccessScene from '../../detail/BuySuccessScene'
import CommonAlertDialog from '../../../widget/dialog/CommonAlertDialog'
export default class ShoppingOrderList extends Component<Props>{

    static navigationOptions = ({navigation}: any) => ({
        headerTintColor: 'black',
        title: '订单列表',
        headerStyle: {backgroundColor: 'white'},
        headerRight: <Text/>,
        headerLeft:<TouchableOpacity onPress={()=>{
            DeviceEventEmitter.emit('orderShop')
        }}>
            <Image style={{marginLeft:12}} source={require('../../../../res/img/gobal_back.png')}/>
        </TouchableOpacity>,

    })

    AliPay = async() => {

        this.setState({
            alipy:require('../../../../res/img/detail/detail_select.png'),
            wechat:require('../../../../res/img/detail/detail_un_select.png'),
            payment:'alipay',
        })
    }

    constructor(props){
        super(props);
        this.state = {
            wechat:require('../../../../res/img/detail/detail_select.png'),
            alipy:require('../../../../res/img/detail/detail_un_select.png'),
            showData:[],
            isShowAll:false,
            address:{},
            isShow:false,
            couponData:[],
            selectIndex:0,
            youhuiPrice:0,
            data:[],
            price:0,
            totalPrice:0,
            coupon:null,
            payment:'wxpay',
            payShow:false,
            orderSn:null,
            show_alert:false,
        }
        XPay.setAlipayScheme('alipayDemo')
        XPay.setWxId('wx8ad5c98436e7aefa')
        this.gobalCoupon = []
        this.couponId = -1

    }
    componentDidMount() {
        const {res} = this.props.navigation.state.params
        let dataList = res.course
        let tempStatusArr = []
        for (let j = 0; j < dataList.length; j++) {
            console.log('item',item)
            let item = dataList[j]
            if (item.coupon){
                let coupon = item.coupon
                item.couponTitle = coupon.title
                item.distance = '此券可用，去结算立减' + coupon.price + '元'
                item.distancePrice = coupon.price
                item.couponId = coupon.id
                this.gobalCoupon.push(coupon.id)
            } else {
                item.couponTitle = '请选择优惠券'
                item.distance = ''
                item.distancePrice = 0
                item.couponId = 0
            }
            tempStatusArr.push(item)
        }
        if (res.course.length > 2){
            let tempStatus = tempStatusArr.slice(0,2)
            this.setState({showData:tempStatus,isShowAll:false,address:res.address,data:tempStatusArr})
        } else {

            this.setState({showData:tempStatusArr,address:res.address,data:tempStatusArr})
        }
        this.calculatePrice(tempStatusArr)
        DeviceEventEmitter.addListener('orderShop', () => {
            this.setState({payShow: true,})
        });
    }
    pay(){
        if (this.state.orderSn){
            fetchGetRequest(api.queryPay, method.get, {orderSn:this.state.orderSn})
                .then(res=>{
                    if (res.status == 'unpaid'){
                        this.setState({show_alert:true})
                    }
                })
                .catch(err=>{
                    Tips.showInfo(err,{mask:true})
                })
            return
        }

        var courseStr = ''
        var couponStr = '['
        this.state.data.forEach(info=>{
            courseStr = courseStr + info.id + ','
            couponStr = couponStr + '(' + info.id + ',' + info.couponId + '),'
        })
         let  params = {
                productId:courseStr,
                payment:this.state.payment,
                clientType:'app',
                addressId:this.state.address.id,
                coupon: couponStr + ']'
            }
        fetchGetRequest(api.sponsorPay,method.get,params)
            .then(res=>{
                console.log(res.payParam)
                // if (res.payParam) {
                this.setState({orderSn:res.orderSn})
                this.sponsorPay(res.payParam)

                // }else {
                //     fetchGetRequest(api.sponsorPay,method.get,params)
                //         .then(res=>{
                //             console.log(res.payParam)
                //             this.sponsorPay(res.payParam)
                //
                //         })
                //         .catch(err=>{})
                // }

            })
            .catch(err=>{
                Tips.showInfo(err,{mask:true})
            })
    }
    sponsorPay(params) {
        if(this.state.payment == 'alipay'){
            XPay.alipay(params,(res)=>{
                if (res.resultStatus == '9000') {
                    Tips.showSuccess('购买成功',{mask:true})
                    this.props.navigation.navigate('BuySuccessScene')

                }else if(res.resultStatus == '8000'){
                    Tips.showInfo('支付确认中...',{mask:true})
                }else {
                    Tips.showFail('购买失败',{mask:true})
                }
            })

        }else if(this.state.payment == 'wxpay'){
            let wechat_params = {
                partnerId:params.partnerid,
                prepayId: params.prepayid,
                packageValue:params.package,
                nonceStr: params.noncestr,
                timeStamp: params.timestamp,
                sign: params.sign,
            }
            XPay.wxPay(wechat_params,(res)=>{
                console.log('res wchat',res)
                if(res.errCode == 0){
                    Tips.showSuccess('购买成功',{mask:true})
                    this.props.navigation.navigate('BuySuccessScene')

                }else {
                    Tips.showFail('购买失败',{mask:true})
                }
            })
        }


    }

    wechat = async() =>{
        this.setState({
            wechat:require('../../../../res/img/detail/detail_select.png'),
            alipy:require('../../../../res/img/detail/detail_un_select.png'),
            payment:'wxpay',
        })
    }
    calculatePrice(data) {
        let tempTotalPrice = 0
        let totalPrice = 0
        let tempStatus = data
        let youhuiPrice = 0
        for (let j = 0; j < tempStatus.length; j++) {
            let item = tempStatus[j]
            totalPrice += item.price
            if ((item.price - item.distancePrice) > 0) {
                tempTotalPrice += (item.price - item.distancePrice)
                youhuiPrice += item.distancePrice
            }else {
                tempTotalPrice += 0
                youhuiPrice += item.price
            }
        }
        this.setState({price: tempTotalPrice, youhuiPrice: youhuiPrice, totalPrice:totalPrice})
    }
    mapcoupondata(res){
        let dataList = res.coupon.map((info) => {
            return {
                id: info.id,
                title: info.title,
                count: info.count,
                price: info.price,
                status: info.status,
                start_datetime: info.start_datetime,
                end_datetime: info.end_datetime,
                coupon_sn: info.coupon_sn,
            }
        })


        return dataList
    }
    filterArrayData(dataList){
        var gobalCoupon = this.gobalCoupon

        for (let i = dataList.length - 1; i >= 0; i--) {
            let kkitem = dataList[i]
            gobalCoupon.forEach(id=>{
                if (kkitem.id == id){
                    dataList.splice(i,1)
                }
            })
        }

        return dataList
    }

    getCouponData(course){
        this.setState({isShow:true})

        let params = {
            course:course.id,
        }
        fetchGetRequest(api.coupon_find,method.get,params)
            .then(res=>{
                let dataList = this.mapcoupondata(res)


                let data =  this.filterArrayData(dataList)
                console.log('yy',data)

                this.setState({couponData:data})

            })
            .catch(err=>{})
    }


    renderAll(index){
        const {res} = this.props.navigation.state.params

        if (index==0 && res.course.length > 2){
            return <TouchableOpacity style={{flexDirection:'row'}} onPress={()=>{
                let isshow = !this.state.isShowAll
            this.setState({isShowAll:isshow})
                if (isshow){
                    let dataList = this.state.data.slice(2)
                    let showData = this.state.showData
                    showData = showData.concat(dataList)
                    this.setState({showData:showData})
                    this.calculatePrice(this.state.data)

                }else {
                    let dataList = this.state.data
                    this.setState({showData:dataList.slice(0,2)})
                    this.calculatePrice(this.state.data)

                }

            }}>
                <Text style={{color:'#999999',fontSize:12}}>查看全部</Text>
                <Image style={{width:7,height:12,marginLeft:7}} source={require('../../../../res/img/gobal_arrow.png')}/>
            </TouchableOpacity>
        } else {
            return <View/>
        }
    }
    renderItem = (rowData:any)=>{
        let course = rowData.item
        let index = rowData.index
        let start_time = course.start_date.substr(5,5).replace('-','月')+'日'
        let end_time = course.end_date.substr(5,5).replace('-','月')+'日'
        let mas_ta = course.teacher[0]
        let tou_ta = course.teacher[1]

        return <View style={{marginLeft:20,marginRight:20}}>
            <View style={{flexDirection:'row',backgroundColor:'white',marginTop:10}}>
                <Text numberOfLines={1} style={styles.title}>{course.title}</Text>
                {this.renderAll(index)}
            </View>
            <View style={{flexDirection:'row',backgroundColor:'white',marginTop:10,alignItems:'center',}}>
                <Image style={{width:12,height:12}} source={require('../../../../res/img/select/select_time.png')}/>
                <Text style={[styles.time,{marginLeft:7}]}>{start_time+'到'+end_time+course.frequency+course.start_time+'-'+course.end_time}</Text>
            </View>
            <View style={{flexDirection:'row',backgroundColor:'white',marginTop:8,alignItems:'flex-end',}}>
                <View style={{flexDirection:'row',alignItems:'center',}}>
                    <Image style={{width:28,height:28,borderRadius:14}} source={{uri:mas_ta.image}}/>
                    <View style={{marginLeft:10,justifyContent:'center',height:28}}>
                        <Text style={styles.teacher}>讲师</Text>
                        <Text style={styles.teacher_show}>{mas_ta.realname}</Text>
                    </View>
                </View>
                <View style={{flexDirection:'row',alignItems:'center',marginLeft:30}}>
                    <Image style={{width:28,height:28,borderRadius:14}} source={{uri:tou_ta.image}}/>
                    <View style={{marginLeft:10,justifyContent:'center',height:28}}>
                        <Text style={styles.teacher}>辅导</Text>
                        <Text style={styles.teacher_show}>{tou_ta.realname}</Text>
                    </View>
                </View>
                <View style={{flex:1}}/>
                <View style={{flexDirection:'row',alignItems:'center'}}>
                    <Image style={{width:7,height:8,marginTop:7}} source={require('../../../../res/img/select/select_price.png')}/>
                    <Text style={styles.price}>{course.price}</Text>
                </View>
            </View>
            <TouchableOpacity style={{marginTop:10,flex:1,height:24,width:width}} onPress={()=>{
                this.couponId = course.couponId
                this.getCouponData(course)
                this.setState({selectIndex:index})
            }}>
                <Image style={{width:(width-40),height:24 ,position:'absolute'}} source={require('../../../../res/img/detail/order_course_bg.png')}/>
                <View style={{marginTop:9, flexDirection:'row',paddingLeft:8}}>
                    <Text style={{color:'#DB3843', fontSize:10,marginTop:1}}>{course.couponTitle}</Text>
                    <Text style={{color:'#333333', fontSize:10,marginLeft:8}}>{course.distance}</Text>
                </View>
            </TouchableOpacity>
        </View>
    }
    addressRequestData = async() =>{

        let json = await NetTool.fetchGetRequest(api.getUserAddr,method.get)

        if (json.addrList.length > 0){
            let address = json.addrList[0]

            this.setState({address:address})
        }else {
            this.setState({address:{}})
        }





    }
    _keyExtractor = (item, index) => index + '';

    renderFooterView=()=>{
        const {res} = this.props.navigation.state.params
        let address = this.state.address
        let dis = this.state.youhuiPrice==0?0:-this.state.youhuiPrice
        // let shi = (this.state.price-this.state.youhuiPrice)<=0?0:(this.state.price-this.state.youhuiPrice)
        return <View>
            <View style={{flexDirection:'row',alignItems:'center',marginTop:15,marginBottom:10,marginLeft:12,}}>
                <Text style={styles.big_title}>讲义派送地址</Text>
                <View style={{flex:1}}/>
                <TouchableOpacity onPress={()=>{
                    fetchGetRequest(api.getUserAddr, method.get)
                        .then(res=>{
                            if (res.addrList.length > 0) {
                                this.props.navigation.navigate('MineAddressScene',{isOrder:true,callback:(data)=>{
                                        this.addressRequestData()
                                    }})
                            }else {
                                this.props.navigation.navigate('AddAddressScene',{isOrder:true,callback:(data)=>{
                                        this.addressRequestData()
                                    }})
                            }
                        })
                        .catch(err=>{})
                }} style={{flexDirection:'row',height:19,borderWidth:1,borderRadius:3,borderColor:'#B0B0B0',alignItems:'center',marginRight:20}}>
                    <Image style={{width:9,height:10,marginLeft:5, marginRight:2}} source={require('../../../../res/img/detail/order_edit.png')}/>
                    <Text style={{fontSize:12,color:'#202020',fontWeight:'200',marginRight:4}}>修改</Text>
                </TouchableOpacity>
            </View>
            <View style={styles.title_view}>
                <Text style={styles.title_show}>收货人：</Text>
                <Text style={styles.title_data}>{address.receiver}</Text>
            </View>
            <View style={styles.title_view}>
                <Text style={styles.title_show}>联系电话：</Text>
                <Text style={styles.title_data}>{address.mobile}</Text>
            </View>
            <View style={styles.title_view_address}>
                <Text style={styles.title_show}>具体地址：</Text>
                <Text numberOfLines={1} style={styles.title_data1}>{address.city_name + address.address}</Text>
            </View>
            <View style={{flexDirection:'row',backgroundColor:'rgba(0,0,0,0.1)',width:(width),height:1,}}/>
            <Text style={[styles.big_title,{marginLeft:12,marginTop:15,marginBottom:10,}]}>结算</Text>
            <View style={styles.title_view}>
                <Text style={styles.title_show_jie_e}>订单金额</Text>
                <View style={{flex:1,}}/>
                <Text style={styles.title_data_jie_e}>{this.state.totalPrice}</Text>
            </View>
            <View style={styles.title_view}>
                <Text style={styles.title_show_jie_e}>优惠金额</Text>
                <View style={{flex:1,}}/>
                <Text style={styles.title_data_jie_e}>{dis}</Text>
            </View>
            <View style={styles.title_view}>
                <Text style={styles.title_show_jie_e}>应付金额</Text>
                <View style={{flex:1,}}/>
                <Text style={styles.title_data_jie_e}>{this.state.price}</Text>
            </View>
            <View style={{flexDirection:'row',backgroundColor:'rgba(0,0,0,0.1)',width:(width),height:1,marginTop:5}}/>
            <Text style={[styles.big_title,{marginTop:15, marginBottom:10, marginLeft:12,}]}>支付方式</Text>
            <TouchableOpacity style={styles.pay_view} onPress={this.AliPay}>
                <Image source={require('../../../../res/img/detail/alipay.png')}/>
                <View style={{marginLeft:27,flexDirection:'column'}}>
                    <Text style={styles.pay_title}>支付宝支付</Text>
                    <Text style={styles.pay_small_title}>Alipay to pay</Text>
                </View>
                <View style={{flex:1}}/>
                <TouchableOpacity style={{width:21,height:21}} onPress={this.AliPay}>
                    <Image source={this.state.alipy}/>
                </TouchableOpacity>
            </TouchableOpacity>
            <TouchableOpacity style={styles.pay_view} onPress={this.wechat}>
                <Image source={require('../../../../res/img/detail/weichat.png')}/>
                <View style={{marginLeft:27,flexDirection:'column'}}>
                    <View style={{flexDirection:'row'}}>
                        <Text style={styles.pay_title}>微信支付</Text>
                        <View style={{backgroundColor:'#835110',borderRadius:3,marginLeft:6,paddingLeft:5,paddingRight:5,paddingTop:1,paddingBottom:1,alignItems:'center',justifyContent:'center'}}>
                            <Text style={{color:'white',fontSize:10,fontWeight:'200'}}>推荐</Text>
                        </View>
                    </View>
                    <Text style={styles.pay_small_title}>WeChat payment</Text>
                </View>
                <View style={{flex:1}}/>
                <TouchableOpacity style={{width:21,height:21}} onPress={this.wechat}>
                    <Image source={this.state.wechat}/>
                </TouchableOpacity>
            </TouchableOpacity>
        </View>
    }
    render(){

        return <SafeAreaView style={{backgroundColor:'white',flex:1}}>
            <FlatList
                data={this.state.showData}
                keyExtractor={this._keyExtractor}
                renderItem={this.renderItem}
                ListHeaderComponent={()=><Text style={[styles.big_title,{marginLeft:12,marginTop:15,}]}>课程信息</Text>}
                ListFooterComponent={this.renderFooterView}
            />
            <UseCouponDialog data={this.state.couponData} show={this.state.isShow} closeModal={(show) => {
                this.setState({isShow: show})
            }} callBack={(info) => {
                if (this.couponId >= 0){
                    for (let i = this.gobalCoupon.length - 1; i >= 0; i--) {
                        let kkitem = this.gobalCoupon[i]
                        if (kkitem == this.couponId) {
                            this.gobalCoupon.splice(i, 1)
                        }

                    }
                }

                let distinct = '此券可用，去结算立减' + info.price + '元'
                let item = this.state.data[this.state.selectIndex]
                item.couponTitle = info.title
                item.distance = distinct
                item.distancePrice = info.price
                item.couponId = info.id
                let gobalCoupon = this.gobalCoupon
                gobalCoupon.push(info.id)
                this.calculatePrice(this.state.data)

            }} cancelPress={() => {
                let item = this.state.data[this.state.selectIndex]
                for (let i = this.gobalCoupon.length - 1; i >= 0; i--) {
                    let kkitem = this.gobalCoupon[i]
                    if (kkitem == item.couponId) {
                        this.gobalCoupon.splice(i, 1)
                    }
                }
                item.couponTitle = '请选择优惠券'
                item.distance = ''
                item.distancePrice = 0
                item.couponId = 0
                this.calculatePrice(this.state.data)
            }}/>
            <CommonAlertDialog show={this.state.payShow} title={'确定放弃支付吗？'} onPress={()=>{
                this.props.navigation.goBack()
            }} closeModal={(st)=>{
                this.setState({payShow:st})
            }} confirmTitle={'确定'}/>
            <CommonAlertDialog show={this.state.show_alert} title={'该课程已生成订单！'} onPress={()=>{
                this.props.navigation.navigate('MineOrderScene',{number:1})
            }} closeModal={(st)=>{
                this.setState({show_alert:st})
            }} confirmTitle={'去支付'}/>
            <TouchableOpacity style={{height:50,backgroundColor:color.globalMainColor,alignItems:'center',justifyContent:"center"}}
                              onPress={()=>{
                                  if (!this.state.address.id){
                                      Tips.showWarn('请选择地址',{mask:true})
                                      return
                                  }else {
                                      this.pay()
                                  }
                              }}>
                <Text style={{fontSize:16,fontWeight:'bold',color:'white'}}>支付</Text>
            </TouchableOpacity>
        </SafeAreaView>
    }
}
const styles = StyleSheet.create({
    big_title : {
        fontWeight:'bold',
        fontSize:16,
        color:'black',

    },
    title_show:{
        color:'rgba(0,0,0,0.5)',
        fontWeight:'200',
        fontSize:12,
        width:64,
    },
    title_data:{
        color:'black',
        fontSize:13,
        marginLeft:8,
        width:200,
    },
    title_data1:{
        color:'black',
        fontSize:13,
        marginLeft:8,
        width:(width - 40 - 24 - 70),
    },
    title_view:{
        flexDirection:'row',
        backgroundColor:'white',
        marginBottom:8,
        alignItems:'center',
        marginLeft:20,
    },
    title_view_address:{
        flexDirection:'row',
        backgroundColor:'white',
        marginBottom:10,
        // alignItems:'center',
        marginLeft:20,
    },
    title_show_jie_e:{
        color:'rgba(0,0,0,0.7)',
        fontWeight:'bold',
        fontSize:12,
    },
    title_data_jie_e:{
        color:'rgba(0,0,0,0.8)',
        fontSize:14,
        fontWeight:'700',
        marginRight:20,
    },
    pay_view:{
        paddingLeft:20,
        paddingRight:20,
        marginBottom:10,
        backgroundColor:'white',
        flexDirection:'row',
        alignItems:'center',
    },

    pay_title:{
        color:'rgba(0,0,0,0.7)',
        fontSize:13,
        fontWeight:'bold',
    },
    pay_small_title:{
        marginTop:3,
        color:'rgba(0,0,0,0.3)',
        fontSize:10,
        fontWeight:'bold',
    },
    title:{
        fontWeight:'bold',
        color:'rgba(0,0,0,0.8)',
        fontSize:16,
        width:(width -100),
    },
    time:{
        fontSize:12,
        color:'#999999',
        fontWeight:'200',
    },
    teacher:{
        fontSize:9,
        color:'#333333',
    },
    teacher_show:{
        fontSize:9,
        color:'#999999',
        marginTop:4,
    },
    price:{
        color:'rgba(197, 50, 60, 1)',
        fontSize:19,
        fontWeight:'700',
        marginLeft:6,
    }

})